package com.example.demo.算法_test.graph;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: java_base
 * @description: 树的宽度优先遍历
 * @author: zhouhongtao
 * @happyCreateTime: 2022/03/15 08:57
 */
public class BFSGraph {

    class Node {
        int value;
        List<Node> neighbors;
    }

    // 宽度优先遍历：使用栈结构
    public void bfs(Node node) {
        if (node == null) {
            return;
        }
        // 因为可能存在环结构，顾需要存储遍历过的点
        HashSet used = new HashSet();
        LinkedList<Node> queue = new LinkedList<>();
        used.add(node);
        queue.push(node);
        while (!queue.isEmpty()) {
            Node pop = queue.poll();
            System.out.println(pop.value);
            List<Node> neighbors = pop.neighbors;
            for (Node node1: neighbors) {
                if (!used.contains(node1)) {
                    queue.push(node1);
                    used.add(node1);
                }
            }
        }
    }
}
